package com.lvyq.myplayer.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.parcelable.SongInfoData
import com.squareup.picasso.Picasso
import jp.wasabeef.picasso.transformations.RoundedCornersTransformation

/**
 * 文件描述：IndexLastSongAdapter 最新单曲
 * 作者：lvyq
 * 创建时间：2025-04-16
 * 修改时间：2025-04-16
 */
class IndexLastSongAdapter(var context:Context?,var list:List<SongInfoData>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    // 定义点击事件接口
    interface OnItemClickListener {
        fun onItemClick(data: SongInfoData, position: Int)
    }

    private var onItemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val itemView = View.inflate(context, R.layout.item_index_last_song,null)
        itemView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                itemView.viewTreeObserver.removeOnGlobalLayoutListener(this)

                val screenWidth = context?.resources?.displayMetrics?.widthPixels
                val cellWidth = screenWidth?:900
                // 安全更新布局参数
                (itemView.layoutParams as? RecyclerView.LayoutParams)?.let { params ->
                    //调整宽度为屏幕的7/8
                    params.width = cellWidth*7/8
                    itemView.layoutParams = params
                }
            }
        })

        itemView.setOnClickListener {  }
        return IndexLastSongViewHolder(itemView)
    }



    override fun getItemCount(): Int {
        return list.size;
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        var data = list.get(position)
        (holder as IndexLastSongViewHolder).setData(data)
        //添加点击事件
        holder.itemView.setOnClickListener {
            onItemClickListener?.onItemClick(data,position)
        }
    }


     inner class IndexLastSongViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
         val  bgImg: ImageView
         val  title: TextView
         val  singer: TextView

         init {
             bgImg=itemView.findViewById(R.id.bgImg)
             title=itemView.findViewById(R.id.title)
             singer=itemView.findViewById(R.id.singer)
         }
         fun setData(data: SongInfoData){
             Picasso.with(context).load(data.bgImg).transform(RoundedCornersTransformation(30,0)).into(bgImg)
             title.text=data.title
             singer.text=data.albumName+"-"+data.singer
         }

     }


}